package com.shp.listener;

import com.shp.pojo.User;
import com.shp.service.ViewsService;
import com.shp.utils.OnlineUserUtil;
import com.shp.utils.ViewData;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Description:
 * session监听器
 * @author zwl
 * @version 1.0
 * @date 2020/3/19 4:17
 */
@WebListener
public class MySessionListener implements HttpSessionListener {

    @Override
    public void sessionCreated(HttpSessionEvent se) {
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        // 获取Spring中的bean
        ViewsService viewsService = MyServletContextListener.getIoc().getBean(ViewsService.class);
        HttpSession session = se.getSession();
        // 如果游客离线
        if(ViewData.viewsMap.contains(session)){
            // 更新数据库游客的访问记录
            viewsService.updateViews(ViewData.viewsMap.get(session.getId()));
        }
        // 如果是游客，移除游客的session
        ViewData.viewsMap.remove(session.getId());
        // 如果是用户，则移除用户session即标志
        OnlineUserUtil.getSessionMap().remove(session.getId());
        if(session.getAttribute("activeUser") != null){
            OnlineUserUtil.getUserEmailList().remove(((User)session.getAttribute("activeUser")).getEmail());
        }
    }
}
